package com.chungkui.check.expression.decorator.impl;

import com.chungkui.check.core.bean.CheckResult;
import com.chungkui.check.expression.MatchExpression;
import com.chungkui.check.expression.decorator.ExpressionDecorator;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * 校验前置条件管理器
 */
public class ConditionExpressionDecorator extends ExpressionDecorator {
    private Expression condition;
    private final Logger log = LoggerFactory.getLogger(ConditionExpressionDecorator.class);

    public ConditionExpressionDecorator(MatchExpression matchExpression) {
        super(matchExpression);
    }

    public static ExpressionDecorator decorator(MatchExpression matchExpression) {
        return new ConditionExpressionDecorator(matchExpression);
    }

    @Override
    public CheckResult match(Map<String, Object> params) {
        boolean result;
        if (this.condition != null) {
            try {
                result = (Boolean) this.condition.execute(params);
            } catch (Exception e) {
                result = false;
                log.info("condition match fail", e);
            }
            //不触发
            if (!result) {
                return CheckResult.success();
            }
        }

        return super.match(params);
    }

    @Override
    public void compile(Map<String, Object> config) {
        String conditionConfig = MapUtils.getString(config, "condition");
        if (StringUtils.isNotEmpty(conditionConfig)) {
            this.condition = AviatorEvaluator.compile(conditionConfig);
        }
        super.compile(config);
    }
}
